package org.JWCB.judge.service;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.JWCB.api.domain.judge.dto.JudgeSubmitDto;
import org.JWCB.api.domain.judge.vo.UserExeResItem;
import org.JWCB.api.domain.judge.vo.UserQuestionResVo;
import org.JWCB.common.core.constants.JudgeConstants;
import org.JWCB.common.core.enums.CodeRunStatus;
import org.JWCB.common.core.enums.SubmitResType;
import org.JWCB.judge.domain.entity.UserSubmit;
import org.JWCB.judge.domain.vo.SandBoxExecuteRes;
import org.JWCB.judge.mapper.JudgeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class JudgeService {


    @Value("${submit.maxExeMessageLen:500}")
    private Integer maxExeMessageLen;
    @Autowired
    private SandBoxPoolService sandBoxPoolService;

    @Autowired
    private JudgeMapper judgeMapper;
    /**
     * 执行java代码
     */
    public UserQuestionResVo doJudgeJavaCode(JudgeSubmitDto judgeSubmitDto) {
        SandBoxExecuteRes sandBoxExecuteRes = sandBoxPoolService.exeJavaCode(judgeSubmitDto);
        UserQuestionResVo userQuestionResVo = new UserQuestionResVo();
        if(sandBoxExecuteRes != null && sandBoxExecuteRes.getRunStatus().equals(CodeRunStatus.SUCCESS)) {
            resultCheck(judgeSubmitDto, sandBoxExecuteRes, userQuestionResVo);
        }else{
            if(sandBoxExecuteRes == null) {
                userQuestionResVo.setPass(CodeRunStatus.UNKNOWN_FAILED.getValue());
                userQuestionResVo.setErrorMsg(CodeRunStatus.UNKNOWN_FAILED.getMsg());
            }else {
                userQuestionResVo.setPass(SubmitResType.FAILED_EXE.getValue());
                userQuestionResVo.setErrorMsg(sandBoxExecuteRes.getExeMessage());
            }
            userQuestionResVo.setScore(JudgeConstants.ERROR_SCORE);
        }

        saveUserSubmit(judgeSubmitDto,userQuestionResVo);
        return userQuestionResVo;
    }

    private  void resultCheck(JudgeSubmitDto judgeSubmitDto, SandBoxExecuteRes sandBoxExecuteRes, UserQuestionResVo userQuestionResVo) {
        List<String> exeOutput = sandBoxExecuteRes.getOutputList();
        List<String> outputList = judgeSubmitDto.getOutputList();
        if(exeOutput.size() != outputList.size()) {
            userQuestionResVo.setScore(JudgeConstants.ERROR_SCORE);
            userQuestionResVo.setPass(SubmitResType.ERROR.getValue());
            userQuestionResVo.setErrorMsg(CodeRunStatus.NOT_PASS_ALL_CASE.getMsg());
        }else {
            boolean pass = true;
            List<UserExeResItem> userExeResItemList = new ArrayList<>();
            for (int index = 0; index < outputList.size(); index++) {
                UserExeResItem userExeResItem = new UserExeResItem();
                userExeResItem.setInput(judgeSubmitDto.getInputList().get(index));
                userExeResItem.setOutput(judgeSubmitDto.getOutputList().get(index));
                userExeResItem.setActualOutput(sandBoxExecuteRes.getOutputList().get(index));
                if(!outputList.get(index).equals(exeOutput.get(index))) {
                    pass = false;
                }
                userExeResItemList.add(userExeResItem);
            }
            userQuestionResVo.setUserExeResItemList(userExeResItemList);
            if(!pass) {
                resFail(userQuestionResVo,SubmitResType.ERROR.getValue(),SubmitResType.ERROR.getDesc());
            }else {
                if(sandBoxExecuteRes.getUseMemory() > judgeSubmitDto.getSpaceLimit()) {
                    resFail(userQuestionResVo,SubmitResType.FAILED_EXE.getValue(),CodeRunStatus.OUT_OF_MEMORY.getMsg());
                } else if(sandBoxExecuteRes.getUseTime() > judgeSubmitDto.getTimeLimit()) {
                    resFail(userQuestionResVo,SubmitResType.FAILED_EXE.getValue(),CodeRunStatus.OUT_OF_TIME.getMsg());
                }else {
                    userQuestionResVo.setScore(JudgeConstants.DEFAULT_SCORE * judgeSubmitDto.getDifficulty());
                    userQuestionResVo.setPass(SubmitResType.PASS.getValue());
                }
            }
        }
    }


    /**
     * 结果失败封装
     */
    private void resFail(UserQuestionResVo questionResVo,int pass,String errorMsg) {
        questionResVo.setScore(JudgeConstants.ERROR_SCORE);
        questionResVo.setPass(pass);
        questionResVo.setErrorMsg(errorMsg);
    }

    /**
     * 保存到db
     */
    private void saveUserSubmit(JudgeSubmitDto judgeSubmitDto,UserQuestionResVo userQuestionResVo) {
        UserSubmit userSubmit = getUserSubmit(judgeSubmitDto, userQuestionResVo);
        judgeMapper.delete(new LambdaQueryWrapper<UserSubmit>()
                .eq(UserSubmit::getUserId,userSubmit.getUserId())
                .eq(UserSubmit::getQuestionId,userSubmit.getQuestionId())
                .isNull(userSubmit.getExamId() == null,UserSubmit::getExamId)
                .eq(userSubmit.getExamId() != null, UserSubmit::getExamId,userSubmit.getExamId()));
        judgeMapper.insert(userSubmit);
    }



    // 组装userSubmit
    private  UserSubmit getUserSubmit(JudgeSubmitDto judgeSubmitDto, UserQuestionResVo userQuestionResVo) {
        UserSubmit userSubmit = new UserSubmit();
        userSubmit.setUserId(judgeSubmitDto.getUserId());
        userSubmit.setExamId(judgeSubmitDto.getExamId());
        userSubmit.setProgramType(judgeSubmitDto.getProgramType());
        userSubmit.setQuestionId(judgeSubmitDto.getQuestionId());
        userSubmit.setUserCode(judgeSubmitDto.getUserCode());
        userSubmit.setPass(userQuestionResVo.getPass());
        if(userQuestionResVo.getErrorMsg() != null) {
            userSubmit.setExeMessage(userQuestionResVo.getErrorMsg().length() >= maxExeMessageLen ? userQuestionResVo.getErrorMsg().substring(0,maxExeMessageLen) : userQuestionResVo.getErrorMsg());
        }
        userSubmit.setScore(userQuestionResVo.getScore());
        userSubmit.setCreateBy(judgeSubmitDto.getUserId());
        userSubmit.setUpdateBy(judgeSubmitDto.getUserId());
        userSubmit.setUniqueId(judgeSubmitDto.getUniqueId());
        userSubmit.setCaseJudgeRes(JSON.toJSONString(userQuestionResVo.getUserExeResItemList()));
        return userSubmit;
    }

}
